//
//  findViewController.m
//  Find
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "FindViewController.h"
#import "FindMessageModel.h"
#import "CollectionViewModel.h"


@interface FindViewController ()

@property (nonatomic, retain)NSMutableArray *dataArray;
@property (nonatomic, retain)NSMutableArray *imageDataArray;

// 标记是否Push 解决 CollectionVIew 多次 push
@property (nonatomic, assign)BOOL isPush;

@end

@implementation FindViewController

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
  
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发现";
     self.view.backgroundColor = [UIColor whiteColor];
    [self addNavBar];
    [self addSubviews];
    
}

#pragma mark --- 获取发现数据
- (void)setUpTableViewData
{
    
    AVQuery *query = [FindMessageModel query];

    // 限制查询返回数
//    query.cachePolicy = kAVCachePolicyCacheElseNetwork;
//    query.maxCacheAge = 60 * 60;

    // 按发帖时间降序排列
    [query orderByDescending:@"createdAt"];
// // 设置缓存策略
//    query.cachePolicy = kAVCachePolicyCacheElseNetwork;
//    // 设置获取本次缓存最大时间 单位 秒
//    query.maxCacheAge = 60 * 60;
       // 限制查询返回数

    [query setLimit:self.limit];
   
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.dataArray = [NSMutableArray arrayWithArray:objects];
        self.imageDataArray = [NSMutableArray array];
        for (FindMessageModel *model in objects) {
            NSString *urlString = [model.imageArray firstObject];
            if (urlString) {
                CollectionViewModel *imageModel = [[CollectionViewModel alloc] init];
                imageModel.picUrl = urlString;
                imageModel.objectID = model.objectId;
                imageModel.title = model.title;
                [self.imageDataArray addObject:imageModel];
             
            }
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self.collectionView reloadData];
            // 下拉结束刷新
            [self.tableView.header endRefreshing];
            // 上拉结束刷新
            [self.tableView.footer endRefreshing];

        });
    }];
}
#pragma mark -- navBar设置
- (void)addNavBar{
     // 将页面 原点(0,0)移到navigationBar下面 (64,0)
    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 设置navbar左右两边图标的颜色
//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    // 左边
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"setting"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(actionLeft:)];
    self.navigationItem.leftBarButtonItem = left;
    // 右边搜索按钮
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(actionRight:)];
    self.navigationItem.rightBarButtonItem = right;
    
    // 导航条背景图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iconfont-navbar-back"] forBarMetrics:UIBarMetricsDefault];
    
    
    // 标题的view
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kFindNavBarTitleViewWidth, kFindNavBarTitleViewHeight)];
    titleView.backgroundColor = [UIColor clearColor];
//    titleView.layer.cornerRadius = kFindNavBarTitleViewCornerRadius;
    self.navigationItem.titleView = titleView;
    
    // 添加segment
    NSArray *segmentItems = @[@"寻", @"觅"];
    self.segmented = [[UISegmentedControl alloc] initWithItems:segmentItems];
    self.segmented.frame = CGRectMake(0, 0, kFindNavBarTitleViewWidth, kFindNavBarTitleViewHeight);
    self.segmented.backgroundColor = [UIColor colorWithRed:0.035 green:0.580 blue:0.827 alpha:1];
    self.segmented.layer.cornerRadius = kFindNavBarTitleViewHeight/2;
    self.segmented.layer.masksToBounds = YES;
    self.segmented.layer.borderWidth = 1; // 边框宽度
    self.segmented.layer.borderColor = kFindListCellLabelTextColor.CGColor; // 边框颜色
    self.segmented.tintColor = [UIColor whiteColor];
    self.segmented.selectedSegmentIndex = 0;
    
    [self.segmented addTarget:self action:@selector(actionSegmented:) forControlEvents:UIControlEventValueChanged];
    
    [titleView addSubview:self.segmented];
    
  
}
// 左上角 按钮  是一个view 移动出来 移动出去
- (void)actionLeft:(UIBarButtonItem *)sender{
    if (self.sortBgImageView.frame.origin.x == -80) {
        [UIView animateWithDuration:0.3 animations:^{
            self.sortBgImageView.frame = CGRectMake(0, 0, 80, 90);
            self.visualView.alpha = 0.8;
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            self.sortBgImageView.frame = CGRectMake(-80, -90, 80, 90);
            self.visualView.alpha = 0;
        }];
    }
}
// 搜索
- (void)actionRight:(UIBarButtonItem *)sender{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    
}

#pragma mark -- segment
- (void)actionSegmented:(UISegmentedControl *)sender{
    switch (sender.selectedSegmentIndex) {
        case 0:
            [self.view sendSubviewToBack:self.collectionView];
            break;
        case 1:
            [self.view sendSubviewToBack:self.tableView];

            break;
        default:
            break;
    }
}


#pragma mark -- 布局视图
- (void)addSubviews{
 
    // 图片的collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = kFindPhotoSpacing;
    flowLayout.minimumInteritemSpacing = kFindPhotoSpacing;
    flowLayout.itemSize = CGSizeMake(kFindPhotoMainImageViewWidth, kFindPhotoMainImageViewHeight+kFindPhotoAddressImageViewHight);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(kFindPhotoSectionInset, kFindPhotoSectionInset, kFindPhotoSectionInset, kFindPhotoSectionInset);
    // 初始化集合视图
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kTabBarHeight-kNavBarHeight) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    self.collectionView.header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
    
    // 上拉回调
    MJChiBaoZiFooter *collectionfooter = [MJChiBaoZiFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    collectionfooter.automaticallyRefresh = NO;
    self.collectionView.footer = collectionfooter;
    
    // 注册collectionCell
    [self.collectionView registerClass:[FindPhotoCollectionCell class] forCellWithReuseIdentifier:@"FindPhotoCell"];
    // 列表的tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kTabBarHeight-kNavBarHeight) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    self.tableView.header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];

    // 上拉回调
    MJChiBaoZiFooter *footer = [MJChiBaoZiFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyRefresh = NO;
    self.tableView.footer = footer;
    [self addLeft];
}
- (void)loadNewData
{

    self.limit = 10;
    [self setUpTableViewData];
    [self setUpCollectionViewData];

}
- (void)loadMoreData
{
    self.limit = self.limit + 10;
    [self setUpTableViewData];
    [self setUpCollectionViewData];

}



#pragma mark -- 左边按钮布局视图
- (void)addLeft{
    
    // UIVisualEffectView 蒙版  有点模糊的View
    self.visualView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    self.visualView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.visualView.alpha = 0;
    [self.view addSubview:self.visualView];
    
    // 排序的button
    self.sortBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-80, -90, 80, 90)];
    self.sortBgImageView.image = [UIImage imageNamed:@"bubble"];
    [self.view addSubview:self.sortBgImageView];
    self.sortBgImageView.userInteractionEnabled = YES;
    // 地址排序
    self.sortAddressButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sortAddressButton.frame = CGRectMake(0, 23, CGRectGetWidth(self.sortBgImageView.frame), 30);
    self.sortAddressButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.sortAddressButton setTitle:@"地址排序" forState:UIControlStateNormal];
    [self.sortAddressButton addTarget:self action:@selector(actionSortAddressButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.sortBgImageView addSubview:self.sortAddressButton];
    
    // 中间分割线
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.sortAddressButton.frame), CGRectGetMaxY(self.sortAddressButton.frame), CGRectGetWidth(self.sortAddressButton.frame), 3)];
    lineLabel.backgroundColor = [UIColor whiteColor];
    [self.sortBgImageView addSubview:lineLabel];
    
    // 时间排序
    self.sortTimeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sortTimeButton.frame = CGRectMake(CGRectGetMinX(lineLabel.frame), CGRectGetMaxY(lineLabel.frame), CGRectGetWidth(self.sortAddressButton.frame), 30);
    [self.sortTimeButton setTitle:@"时间排序" forState:UIControlStateNormal];
    [self.sortTimeButton addTarget:self action:@selector(actionSortTimeButton:) forControlEvents:UIControlEventTouchUpInside];
    self.sortTimeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.sortBgImageView addSubview:self.sortTimeButton];
}

#pragma mark -- 按地址排序
- (void)actionSortAddressButton:(UIButton *)sender{
    [UIView animateWithDuration:0.3 animations:^{
        self.sortBgImageView.frame = CGRectMake(-80, -90, 80, 90);
        self.visualView.alpha = 0;
    }];
    [self setUpCollectionViewData];

    
}
#pragma ----collectionView的数据 ---
- (void)setUpCollectionViewData
{
    // 距离
    AVQuery *query = [FindMessageModel query];
    [query orderByAscending:@"distance"];
//    query.cachePolicy = kAVCachePolicyCacheElseNetwork;
//    query.maxCacheAge = 60 * 60;
    [query setLimit:self.limit];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        self.dataArray = [NSMutableArray arrayWithArray:objects];
        self.imageDataArray = [NSMutableArray array];
        for (FindMessageModel *model in objects) {
            NSString *urlString = [model.imageArray firstObject];
            if (urlString) {
                CollectionViewModel *imageModel = [[CollectionViewModel alloc] init];
                imageModel.picUrl = urlString;
                imageModel.objectID = model.objectId;
                imageModel.title = model.title;
                [self.imageDataArray addObject:imageModel];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //  [self.tableView reloadData];
            [self.collectionView reloadData];
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
        });
    }];
}
#pragma mark -- 按时间排序
- (void)actionSortTimeButton:(UIButton *)sender{
    [UIView animateWithDuration:0.3 animations:^{
        self.sortBgImageView.frame = CGRectMake(-80, -90, 80, 90);
        self.visualView.alpha = 0;
    }];
    [self setUpTableViewData];
}

#pragma mark -- tableView代理方法
// 每个分区多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

// 每个分区的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return 130;
    /*
    CGFloat cellHeight = kFindListCellMineImageViewY + kFindListCellMineImageViewHeight + kFindListCellDetailLabelToMineImageViewY + kFindListCellDetailLabelHeight + kFindListCellAddressImageViewToDetailLabelY + kFindListCellAddressImageViewHeight + kFindListCellAddressImageViewToDetailLabelY;
    return cellHeight;
     */
}

#pragma mark ----设置cell---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"FindListCell";
    LostListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[LostListTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
     // 获取数据
     FindMessageModel *findModel = self.dataArray[indexPath.row];
    AVUser *user1 = findModel.user;
    //    AVUser *user2 = [AVQuery getUserObjectWithId:user1.objectId];  // 同步请求数据导致界面卡顿
    AVQuery * query = [AVQuery queryWithClassName:@"_User"];
    [query  getObjectInBackgroundWithId:user1.objectId block:^(AVObject *object, NSError *error) {
        cell.listTitleLabel.text =  [object objectForKey:@"username"];
        NSString *urlString = [[object valueForKey:@"photoImage"] getThumbnailURLWithScaleToFit:NO width:100 height:100];
        [cell.listImage sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    }];
    
    // 距离
    AVUser *user = [AVUser currentUser];
    CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:[[user valueForKey:@"latitude"] floatValue] longitude:[[user valueForKey:@"longitude"] floatValue]];
    CLLocation *publishLocation = [[CLLocation alloc] initWithLatitude:[findModel.latitude floatValue] longitude:[findModel.longitude floatValue]];
   
    if ([findModel.latitude floatValue] == 0.0 && [findModel.longitude floatValue]== 0.0) {
        cell.listDistance.text = @"未定位";
    } else {
        CLLocationDistance distance = [userLocation distanceFromLocation:publishLocation];
        findModel.distance =[NSNumber numberWithFloat:distance];
        [findModel saveInBackground];
     if (distance < 1000){
        cell.listDistance.text = [NSString stringWithFormat:@"%dm",(int)distance];
     } else {
         
        cell.listDistance.text = [NSString stringWithFormat:@"%.1fkm",(distance / 1000)];
     }
    }
    // 用户名
    cell.listTextLabel.text = findModel.context;
    // 上传的日期
    NSDateFormatter *dateFoematter = [[NSDateFormatter alloc] init];
    [dateFoematter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSRange range = NSMakeRange(5, 11);
    cell.listTimeLabel.text = [[dateFoematter stringFromDate: findModel.createdAt] substringWithRange:range];
   
    // 位置
    if ([findModel.location isEqualToString:@"(null)"])
    {
        cell.listAddressLabel.text = @"";
    } else {
    cell.listAddressLabel.text = findModel.location;
    }
   
    UIView *selectedView = [[UIView alloc] init];
    selectedView.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = selectedView;
    
    
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = selectView;
    
    return cell;
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *objectID = [self.dataArray[indexPath.row] objectId];
    
    FindDetailViewController *detailVC = [[FindDetailViewController alloc] init];
    detailVC.objectID = objectID;
    detailVC.publishInfoType = @"find";
    

    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark -- collectionView代理方法
// 有多少个分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
// 每个分区多少行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageDataArray.count;
}
// cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FindPhotoCollectionCell *findCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FindPhotoCell" forIndexPath:indexPath];
   
    CollectionViewModel *model = self.imageDataArray[indexPath.row];
    
    NSURL *url = [NSURL URLWithString:model.picUrl];
    [findCell.mainImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder2"]];
    findCell.addressLabel.text = model.title;
    
    return findCell;
}
// 点击cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isPush == NO) {
        
    CollectionViewModel *model = self.imageDataArray[indexPath.row];
    FindDetailViewController *findVC = [[FindDetailViewController alloc] init];
    findVC.objectID = model.objectID;
    
    // 关闭交互
//    [self.collectionView setUserInteractionEnabled:NO];
    [self.navigationController pushViewController:findVC animated:YES];
         }
    else {}
    self.isPush = YES;
}

#pragma mark --- 将要出现的时候打开 collectionView 交互功能
- (void)viewDidAppear:(BOOL)animated
{
    self.isPush = NO;
//    [self.collectionView setUserInteractionEnabled:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
